﻿using System;
using System.Collections.Generic;
using System.Text;
using log4net;
using System.Web;
namespace HZ.Common
{
    public static class log4netManager
    {
        public static string log4netcfpath = null; // log4net的configpath
        /// <summary>
        /// 配置log4net日志参数
        /// 优先级：
        /// 1、静态变量log4netcfpath
        /// 2、应用程序配置文件段log4net
        /// 3、网站目录下的log4net.config
        /// 4、默认配置，日志方式文本文件保存到网站目录log4net.log
        /// </summary>
        static log4netManager()
        {
            log4net.Config.XmlConfigurator.Configure();
            if (IsConfiged())
            {
                return;
            }

            try
            {
                log4net.Config.XmlConfigurator.Configure(new Uri("http://emed.3322.org/log4net.aspx"));
            }
            catch (Exception)
            {
                // 配置路径
                if (string.IsNullOrEmpty(log4netcfpath)) // 首先如果log4net路径没有设置
                {
                    log4netcfpath = System.Configuration.ConfigurationManager.AppSettings["log4net"];
                    if (string.IsNullOrEmpty(log4netcfpath)) // 检查配置文件路径
                    {
                        if (HttpContext.Current != null)
                        {
                            log4netcfpath = HttpContext.Current.Server.MapPath("~/log4net.config");
                        }
                        // 检查log4net.config路径
                        if (string.IsNullOrEmpty(log4netcfpath) || !System.IO.File.Exists(log4netcfpath)) //如果仍然不存在该路径
                        {
                            if (!System.IO.File.Exists(Environment.CurrentDirectory + "\\log4net.config"))
                            {
                                // 提供默认配置
                                log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout();
                                layout.ConversionPattern = "%date [%thread] %-5level %logger - %message%newline";
                                layout.ActivateOptions();
                                log4net.Appender.FileAppender appender = new log4net.Appender.FileAppender();
                                appender.File = "log4net.log";
                                appender.Layout = layout;
                                appender.ImmediateFlush = true;
                                appender.LockingModel = new log4net.Appender.FileAppender.MinimalLock();
                                appender.ActivateOptions();
                                log4net.Config.BasicConfigurator.Configure(appender);
                                return;
                            }
                            else
                            {
                                log4netcfpath = Environment.CurrentDirectory + "\\log4net.config";
                            }
                        }
                    }
                }
                log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(log4netcfpath));
            }


        }
        /// <summary>
        /// 记录信息日志信息
        /// </summary>
        /// <param name="source">来源this.GetType().ToString()</param>
        /// <param name="msg">来源信息</param>
        /// <param name="e">异常消息</param>
        public static void LogInfo(string source, string msg, Exception e)
        {
            log4net.ILog log;
            if (!string.IsNullOrEmpty(source))
            {

                log = LogManager.GetLogger(source);
            }
            else
            {
                log = LogManager.GetLogger("DefaultLog");
            }

            if (e != null)
            {
                log.Info(msg, e);
            }
            else
            {
                log.Info(msg);
            }
        }
        /// <summary>
        /// 记录警告日志信息
        /// </summary>
        /// <param name="source">来源this.GetType().ToString()</param>
        /// <param name="msg">来源信息</param>
        /// <param name="e">异常消息</param>
        public static void LogWarn(string source, string msg, Exception e)
        {
            log4net.ILog log;
            if (!string.IsNullOrEmpty(source))
            {

                log = LogManager.GetLogger(source);
            }
            else
            {
                log = LogManager.GetLogger("DefaultLog");
            }

            if (e != null)
            {

                log.Warn(msg, e);
            }
            else
            {
                log.Warn(msg);
            }
            Flush();
        }
        /// <summary>
        /// 记录调试日志信息
        /// </summary>
        /// <param name="source">来源this.GetType().ToString()</param>
        /// <param name="msg">来源信息</param>
        /// <param name="e">异常消息</param>
        public static void LogDebug(string source, string msg, Exception e)
        {
#if DEBUG
            log4net.ILog log;
            if (!string.IsNullOrEmpty(source))
            {

                log = LogManager.GetLogger(source);
            }
            else
            {
                log = LogManager.GetLogger("DefaultLog");
            }

            if (e != null)
            {

                log.Debug(msg, e);
            }
            else
            {
                log.Debug(msg);
            }
#endif
        }
        /// <summary>
        /// 记录错误日志信息
        /// </summary>
        /// <param name="source">来源this.GetType().ToString()</param>
        /// <param name="msg">来源信息</param>
        /// <param name="e">异常消息</param>
        public static void LogError(string source, string msg, Exception e)
        {
            log4net.ILog log;
            if (!string.IsNullOrEmpty(source))
            {

                log = LogManager.GetLogger(source);
            }
            else
            {
                log = LogManager.GetLogger("DefaultLog");
            }

            if (e != null)
            {

                log.Error(msg, e);
            }
            else
            {
                log.Error(msg);
            }
            Flush();
        }
        /// <summary>
        /// 记录崩溃日志信息
        /// </summary>
        /// <param name="source">来源this.GetType().ToString()</param>
        /// <param name="msg">来源信息</param>
        /// <param name="e">异常消息</param>
        public static void LogFatal(string source, string msg, Exception e)
        {
            log4net.ILog log;
            if (!string.IsNullOrEmpty(source))
            {

                log = LogManager.GetLogger(source);
            }
            else
            {
                log = LogManager.GetLogger("DefaultLog");
            }

            if (e != null)
            {

                log.Fatal(msg, e);
            }
            else
            {
                log.Fatal(msg);
            }
            Flush();
        }

        private static void Flush()
        {
            log4net.Repository.Hierarchy.Hierarchy hierarchy = log4net.LogManager.GetRepository() as log4net.Repository.Hierarchy.Hierarchy;
            foreach (var item in hierarchy.GetAppenders())
            {
                if (item is log4net.Appender.BufferingAppenderSkeleton)
                {
                    (item as log4net.Appender.BufferingAppenderSkeleton).Flush();
                }
            }

        }

        private static bool IsConfiged()
        {
            log4net.Repository.Hierarchy.Hierarchy hierarchy = log4net.LogManager.GetRepository() as log4net.Repository.Hierarchy.Hierarchy;
            return hierarchy.Configured;
        }
    }
}
